package org.zhuzx.util.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.zhuzx.util.MicroUtil;

/**
 * 用于获取容器中的bean对象的工具
 */
@Component
@SuppressWarnings("unchecked")
@Slf4j
public class ApplicationContextBeanUtil implements ApplicationContextAware {
	
	static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		ApplicationContextBeanUtil.applicationContext = applicationContext;
		log.info("容器工具类已加载");
	}

	/**
	 * @param beanNameOrClassName 支持bean名称、简单类名、全限定类名
	 */
	public static <T> T getBean(String beanNameOrClassName) {
		String beanName = StringUtils.uncapitalize(MicroUtil.subBehind(beanNameOrClassName, '.'));
		return (T) applicationContext.getBean(beanName);
	}

	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

}